<?php

namespace App\Service\Cruise\Check;

use App\Enums\BaseErrorCode;
use App\Exceptions\Custom\ResponseHttpException;
use App\Exports\Cruise\CruiseCheck3Export;
use App\Exports\Cruise\CruiseCheck3V2Export;
use App\Exports\Cruise\CruiseCheck5Export;
use App\Library\Rms\RmsShopApi;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyRoleMappingModel;
use App\Models\Common\FsCompanyUserMappingModel;
use App\Models\Common\FsCompanyUserModel;
use App\Models\Cruise\CruiseCheckDetailModel;
use App\Models\Cruise\CruiseCheckTaskGroupModel;
use App\Models\Cruise\CruiseCheckTaskModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseTaskOrderMappingModel;
use App\Models\Cruise\CruiseTemplateModel;
use App\Remote\Orm\OrmNewOrderRemote;
use App\Remote\Rms\RmsShopRemote;
use App\Service\BaseService;
use App\Service\Common\ExportService;
use App\Service\OpenShop\Feishu\SelectionService;
use App\Service\OpenShop\User\RmsUserService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Exceptions\NoTypeDetectedException;
use OSS\Core\OssException;

class CruiseCheckSpecialService extends BaseService
{
    public static function addSelects(int $templateType): array
    {
        return Cache::remember('CruiseCheckSpecialService-addSelect_v2:'.$templateType, 60, function () use ($templateType) {

            // 模板列表
            $templates = CruiseTemplateModel::query()
                                            ->where('type', $templateType)
                                            ->where('sysTemplate', CruiseTemplateModel::TEMPLATE_SPECIAL_SYS[$templateType] ?? 0)
                                            ->where('status', CruiseTemplateModel::STATUS_ON)
                                            ->select('id', 'name')
                                            ->get();

            // 巡检人角色
            $roles = [
                [
                    'text'  => '内部员工',
                    'value' => CruiseCheckDetailModel::CHECK_TYPE_INSIDE,
                ],
                [
                    'text'  => '第三方巡检',
                    'value' => CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY,
                ],
            ];

            // 巡检人
            $users = SelectionService::getManagerList();

            // 巡检机构
            $departmentIds = Cache::remember('companyDepartmentIds', 60, function () {
                return collect(OrmNewOrderRemote::getOrmSupplier(OrmNewOrderRemote::SUPPLIER_TYPE_SERVICE)['data']['list'] ?? [])
                    ->filter(function ($item) {
                        if (!isset($item['code']) && !$item['code']) {
                            return false;
                        }

                        return true;
                    })
                    ->pluck('code')->toArray();
            });

            $companys = FsCompanyModel
                ::query()
                ->whereIn('departmentId', $departmentIds)
                ->where('status', FsCompanyModel::STATUS_ON)
                ->select('departmentId', 'name')
                ->get()
                ->map(function ($item) {
                    return [
                        'id'   => $item->departmentId,
                        'name' => $item->name,
                    ];
                })
                ->toArray();

            return [
                'templates' => $templates,
                'roles'     => $roles,
                'users'     => $users,
                'companys'  => $companys,
            ];
        });
    }

    /**
     * @param string $name
     * @param int $status
     * @param int $pageSize
     * @param int $pageNum
     * @param int $templateType
     * @param int $shopId
     * @param int $checkType
     * @param int $export
     * @return array
     * @throws GuzzleException
     * @throws BindingResolutionException
     * @throws NoTypeDetectedException
     * @throws OssException
     */
    public static function lists(
        string $name,
        int $status,
        int $pageSize,
        int $pageNum,
        int $templateType,
        int $shopId,
        int $checkType,
        int $export
    ): array {

        $specialTemplateIds = CruiseTemplateModel::query()
                                                 ->whereIn('sysTemplate', array_values(CruiseTemplateModel::TEMPLATE_SPECIAL_SYS))
                                                 ->pluck('id');

        // shopId筛选
        $taskIds = [];
        if ($shopId) {
            $taskIds = CruiseCheckTaskGroupModel::query()
                                                ->whereRaw("JSON_CONTAINS(shopIds, JSON_ARRAY({$shopId}}))")
                                                ->groupBy('taskId')
                                                ->pluck('taskId')
                                                ->toArray();
        }

        $exportClass = null;
        if ($export) {
            $exportClass = (new CruiseCheck3V2Export())->setDeleteLocalFile(true);
        }


        $paginator = CruiseCheckTaskModel::query()
                                         ->where('templateType', $templateType)
                                         ->whereIn('templateId', $specialTemplateIds)
                                         ->when(in_array($checkType,
                                             array_keys(CruiseCheckTaskGroupModel::ROLE_TEXT)),
                                             function ($query) use ($checkType) {
                                                 return $query->whereHas("cruiseTaskGroupsRel",
                                                     function ($query) use ($checkType) {
                                                         $query->where("role", $checkType);
                                                     });
                                             })
                                         ->when($name, function ($query) use ($name) {
                                             $query->where('name', 'like', "%{$name}%");
                                         })
                                         ->when($status, function ($query) use ($status) {
                                             $query->where('status', $status);
                                         })
                                         ->when($taskIds, function ($query) use ($taskIds) {
                                             $query->whereIn('id', $taskIds);
                                         })
                                         ->when(
                                             $export,
                                             function ($query) use ($templateType, $exportClass) {
                                                 return $query
                                                     ->with(['cruiseCheckDetailRel.cruiseOrderRel.fsHandlerUserRel'])
                                                     ->with(['cruiseTaskGroupsRel'])
                                                     ->orderByDesc('id')
                                                     ->chunk(50, function ($collection) use ($exportClass) {
                                                         $export = new CruiseCheck3Export($collection);
                                                         $export->array();
                                                         $exportClass->writeContents($export->excelContents);
                                                     });
                                             },
                                             function ($query) use ($pageSize, $pageNum) {
                                                 return $query
                                                     ->orderByDesc('id')
                                                     ->with(['cruiseOrdersRel'])
                                                     ->paginate($pageSize, ['*'], 'pageNum', $pageNum);
                                             },
                                         );



        if ($export) {
            switch ($templateType) {
                case CruiseTemplateModel::TYPE_3:
                    ini_set('memory_limit', '200M');
                    return $exportClass->ossExport();
                    break;
                case CruiseTemplateModel::TYPE_5:
                    return excelDownload(new CruiseCheck5Export($paginator), "工厂专项巡检");
                    break;
            }

        }

        $userIds   = collect($paginator->items())->pluck('createdByUid')->toArray();
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');

        // 判断哪些任务是导入的任务  导入的任务不显示编辑按钮
        $importTaskIds = CruiseCheckTaskGroupModel::query()
            ->whereIn('taskId', collect($paginator->items())->pluck('id')->toArray())
            ->where('source', CruiseCheckTaskGroupModel::SOURCE_IMPORT)
            ->pluck('taskId')
            ->toArray();

        return self::pageLists($paginator, function ($item) use ($userInfos, $importTaskIds) {

            return [
                'id'                => $item->id,
                'name'              => $item->name,
                'startDate'         => date('Y-m-d', $item->startTime),
                'endDate'           => date('Y-m-d', $item->endTime),
                'createdByUserName' => $userInfos[$item->createdByUid]['username'] ?? '',
                'createdAt'         => $item->createdAt->toDateTimeString(),
                'status'            => $item->status,
                'statusText'        => $item->statusText,
                'finishNum'         => $item->cruiseOrdersRel->whereIn('status',
                    [CruiseOrderModel::STATUS_COMPLETE, CruiseOrderModel::STATUS_CLOSED])
                                                             ->count(),
                'planNum'           => $item->cruiseOrdersRel->count(),
                'isShowEdit'        => $item->status == CruiseCheckTaskModel::STATUS_WAIT_PUSH && !in_array($item->id, $importTaskIds),  // 是否展示编辑按钮
            ];
        });
    }

    /**
     * 完成 - 更新status
     * @param int $id
     * @return void
     */
    public static function tryCompleteStatus(int $id): void
    {
        $orderIds = CruiseTaskOrderMappingModel::query()->where('taskId', $id)->pluck('orderId');

        // 所有的order数量
        $orderNum = CruiseOrderModel::query()->whereIn('id', $orderIds)->count();

        // 完成
        $ct = CruiseOrderModel::query()
                              ->whereIn('id', $orderIds)
                              ->whereIn('status', [
                                  CruiseOrderModel::STATUS_COMPLETE,
                                  CruiseOrderModel::STATUS_CLOSED,
                                  CruiseOrderModel::STATUS_AUDIT_OK,
                                  CruiseOrderModel::STATUS_AUDIT_ERROR
                              ])
                              ->count();
        if ($ct == $orderNum) {
            CruiseCheckTaskModel::query()->where('id', $id)->update(['status' => CruiseCheckTaskModel::STATUS_FINISH]);
        }
    }

    /**
     * 完成情况
     * @param int $id
     * @return array[]
     */
    public static function completion(int $id): array
    {
        $task = CruiseCheckTaskModel::query()->where('id', $id)->first();
        if (!$task) {
            BaseService::throwErr('不存在的巡检id');
        }

        if ($task->templateType == CruiseTemplateModel::TYPE_3) {
            $text = '已巡检门店';
        } elseif ($task->templateType == CruiseTemplateModel::TYPE_5) {
            $text = '已巡检供应商';
        } else {
            $text = '已巡检门店';
        }

        $orderIds = CruiseCheckDetailModel::query()->where('taskId', $id)->pluck('orderId');

        return [
            'name'          => $task->name,
            'startDateTime' => date('Y-m-d', $task->startTime),
            'endDateTime'   => date('Y-m-d', $task->endTime),
            'templateText'  => CruiseTemplateModel::query()->where('id', $task->templateId)->value('name') ?? '',
            'completion' => [
                [
                    'text' => $text,
                    'num'  => CruiseOrderModel::query()->whereIn('id', $orderIds)->count(),
                ],
                [
                    'text' => '已提交巡检报告',
                    'num'  => CruiseOrderModel::query()
                                              ->whereIn('id', $orderIds)
                                              ->whereIn('status',
                                                  [
                                                      CruiseOrderModel::STATUS_NOT_REVIEW,
                                                      CruiseOrderModel::STATUS_COMPLETE
                                                  ])
                                              ->count(),
                ],
                [
                    'text' => '已完成巡检报告',
                    'num'  => CruiseOrderModel::query()
                                              ->whereIn('id', $orderIds)
                                              ->where('status', CruiseOrderModel::STATUS_COMPLETE)
                                              ->count(),
                ],
            ]
        ];
    }

    public static function detail(int $id): array
    {
        $task = CruiseCheckTaskModel::query()->with('cruiseTaskGroupsRel')->with('cruiseOrdersRel')->find($id);
        if (!$task) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的巡检id");
        }

        // 准备基础数据
        $shopIds = $userIds = $companyIds = [];
        $task->cruiseTaskGroupsRel->each(function ($item) use (&$shopIds, &$userIds, &$companyIds) {
            $shopIds      = array_merge($shopIds, $item['shopIdsArr']);
            $userIds[]    = $item['userId'];
            $companyIds[] = $item['companyId'];
        });

        $shopIds    = array_unique(array_filter($shopIds));
        $userIds    = array_unique(array_filter($userIds));
        $companyIds = array_unique(array_filter($companyIds));

        $shops     = collect((new RmsShopApi())->getShopByIds($shopIds, [], false)['data']['shopList'] ?? []);
        $userInfos = collect(RmsUserService::getRmsUserInfoByUserIds($userIds)['data'])->keyBy('id');
        $companys  = collect(FsCompanyModel::getCompanyLists())->map(function ($item) {
            return [
                'id'   => $item['departmentId'],
                'name' => $item['name'],
            ];
        })->keyBy('id');

        return [
            'id'            => $id,
            'name'          => $task->name,
            'startDateTime' => date('Y-m-d', $task->startTime),
            'endDateTime'   => date('Y-m-d', $task->endTime),
            'templateId'    => $task->templateId,
            'templateText'  => CruiseTemplateModel::query()->where('id', $task->templateId)->value('name') ?? '',
            'groups'        => $task->cruiseTaskGroupsRel
                ->map(function ($item) use ($shops, $userInfos, $companys, $task) {

//                    if ($task->templateType == CruiseTemplateModel::TYPE_3) {
//                        $taskGroupColumn   = 'shopIdsArr';
//                        $cruiseOrderColumn = 'shopId';
//                        $text              = '已巡检门店';
//                    } elseif ($task->templateType == CruiseTemplateModel::TYPE_5) {
//                        $taskGroupColumn   = 'beCruiseCheckCompanyIdsArr';
//                        $cruiseOrderColumn = 'cruiseCheckCompanyId';
//                        $text              = '已巡检供应商';
//                    } else {
//                        $taskGroupColumn   = 'shopIdsArr';
//                        $cruiseOrderColumn = 'shopId';
//                        $text              = '已巡检门店';
//                    }

                    return
                        [
                            'role'                  => $item->role, // 1内部 2三方
                            'userId'                => $item->userId,
                            'userName'              => $userInfos[$item->userId]['username'] ?? '',
                            'companyId'             => $item->companyId,
                            'companyName'           => $companys[$item->companyId]['name'] ?? '',
                            'shops'                 => [
                                'shopIds'    => $item->shopIdsArr,
                                'totalCount' => count($item->shopIdsArr), // 已选择数量
                                'ingCount'   => $shops->whereIn('id', $item->shopIdsArr)
                                                      ->where('status', RmsShopApi::SHOP_STATUS_NORMAL)
                                                      ->count(), // 营业中
                                'stopCount'  => $shops->whereIn('id', $item->shopIdsArr)
                                                      ->where('status', RmsShopApi::SHOP_STATUS_BAN)
                                                      ->count(), // 停业
                                'notCount'   => $shops->whereIn('id', $item->shopIdsArr)
                                                      ->where('status', RmsShopApi::SHOP_STATUS_PREPARE)
                                                      ->count(), // 未开业
                            ],
                            'shopInfos'   => $shops->whereIn('id', $item->shopIdsArr)->values(),
                            'cruiseCheckCompanyIds' => $item->beCruiseCheckCompanyIdsArr,
//                            'completions' => [
//                                [
//                                    'text' => $text,
//                                    'num'  => count($item->{$taskGroupColumn}),
//                                ],
//                                [
//                                    'text' => '已提交巡检报告',
//                                    'num'  => $task->cruiseOrdersRel->whereIn($cruiseOrderColumn, $item->{$taskGroupColumn})
//                                                                    ->whereIn('status',
//                                                                        [
//                                                                            CruiseOrderModel::STATUS_NOT_REVIEW,
//                                                                            CruiseOrderModel::STATUS_COMPLETE
//                                                                        ])
//                                                                    ->count(),
//                                ],
//                                [
//                                    'text' => '已完成巡检报告',
//                                    'num'  => $task->cruiseOrdersRel->whereIn($cruiseOrderColumn, $item->{$taskGroupColumn})
//                                                                    ->where('status', CruiseOrderModel::STATUS_COMPLETE)
//                                                                    ->count(),
//                                ],
//                            ],

                        ];
                }),
        ];
    }

    /**
     * @param string $name
     * @param int $startTime
     * @param int $endTime
     * @param int $templateId
     * @param array $groups
     * @return int
     */
    public static function add(string $name, int $startTime, int $endTime, int $templateId, array $groups): int
    {
        DB::beginTransaction();

        $taskId = (new CruiseCheckTaskModel([
            'name'         => $name,
            'startTime'    => $startTime,
            'endTime'      => $endTime,
            'templateId'   => $templateId,
            'templateType' => CruiseTemplateModel::query()->where('id', $templateId)->value('type'),
            'status'       => CruiseCheckTaskModel::STATUS_WAIT_PUSH
        ]))->addData()->id;

        CruiseCheckTaskGroupModel::batchAddData(collect($groups)->map(function ($item) use ($taskId) {
            return [
                'taskId'                  => $taskId,
                'source'                  => $item['source'] ?? 0,
                'role'                    => $item['role'],
                'userId'                  => $item['userId'] ?? 0,
                'relationCode'            => $item['relationCode'] ?? '',
                'companyId'               => $item['companyId'] ?? '',
                'shopIds'                 => json_encode($item['shopIds'] ?? []),
                'beCruiseCheckCompanyIds' => json_encode($item['cruiseCheckCompanyIds'] ?? []),
            ];
        }));

        DB::commit();

        return $taskId;
    }

    /**
     * @param int $id
     * @param string $name
     * @param int $startTime
     * @param int $endTime
     * @param int $templateId
     * @param array $groups
     * @return int
     */
    public static function edit(
        int $id,
        string $name,
        int $startTime,
        int $endTime,
        int $templateId,
        array $groups
    ): int {
        $task = CruiseCheckTaskModel::query()->find($id);
        if (!$task) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的巡检id");
        }

        if ($task->status != CruiseCheckTaskModel::STATUS_WAIT_PUSH) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "已推送的巡检无法编辑");
        }

        DB::beginTransaction();

        $task->update([
            'name'       => $name,
            'startTime'  => $startTime,
            'endTime'    => $endTime,
            'templateId' => $templateId,
        ]);

        CruiseCheckTaskGroupModel::query()->where('taskId', $id)->delete();

        CruiseCheckTaskGroupModel::batchAddData(collect($groups)->map(function ($item) use ($id) {

            return [
                'taskId'    => $id,
                'role'      => $item['role'],
                'userId'    => $item['userId'],
                'companyId' => $item['companyId'],
                'shopIds'   => json_encode($item['shopIds']),
                'beCruiseCheckCompanyIds' => json_encode($item['cruiseCheckCompanyIds'] ?? []),
            ];
        }));

        DB::commit();

        return $id;
    }

    public static function offline(int $id, int $userId)
    {
        $task = CruiseCheckTaskModel::query()->find($id);
        if (!$task) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的巡检id");
        }

        if ($task->status == CruiseCheckTaskModel::STATUS_CANCEL) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "无法反复作废");
        }

        if ($task->status == CruiseCheckTaskModel::STATUS_WAIT_PUSH) {
            // 解绑所有任务
            CruiseCheckTaskGroupModel::query()
                ->where('taskId', $id)
                ->update([
                    'relationCode' => ''
                ]);
        } else {
            // 获得没有完成以及待审核中的订单
            $orderIds = CruiseCheckDetailModel::query()
                ->where('taskId', $id)
                ->pluck('orderId')
                ->toArray();

            $delRelationCodes = [];
            CruiseOrderModel::query()
                ->whereIn('id', $orderIds)
                ->where('relationCode', '!=', '')
                ->whereNotIn('status', [CruiseOrderModel::STATUS_COMPLETE, CruiseOrderModel::STATUS_NOT_REVIEW])
                ->get()
                ->map(function (CruiseOrderModel $cruiseOrderModel) use (&$delRelationCodes) {
                    $delRelationCodes[] = $cruiseOrderModel->relationCode;
                    $cruiseOrderModel->relationCode = '';
                    $cruiseOrderModel->save();
                });

            if (count($delRelationCodes)) {
                // 解绑关联code
                CruiseCheckTaskGroupModel::query()
                    ->whereIn('relationCode', $delRelationCodes)
                    ->update([
                        'relationCode' => ''
                    ]);
            }
        }

        $task->status = CruiseCheckTaskModel::STATUS_CANCEL;
        $task->save();


        // 没完成的直接作废
        CruiseTaskOrderMappingModel::query()->where('taskId', $id)->get()->each(function ($item) {
            CruiseCheckTaskService::orderCancel($item->orderId, 0, false);
        });

        // 任务作废推送
        (new CruiseCheckFsService(null, null))->offlineTask($userId, $task);
    }

    public static function push(int $id)
    {
        $task = CruiseCheckTaskModel::query()->with('cruiseTaskGroupsRel')->find($id);
        if (!$task) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "不存在的巡检id");
        }

        if ($task->status != CruiseCheckTaskModel::STATUS_WAIT_PUSH) {
            throw new ResponseHttpException(BaseErrorCode::$ERROR_OCCURRED, null, "已推送无法重复操作");
        }

        // 判断服务单号是否重复
        $taskGroupRelationCode = CruiseCheckTaskGroupModel::query()
            ->where('taskId', $id)
            ->pluck('relationCode')
            ->toArray();

        $filterTaskGroupRelationCode = array_filter($taskGroupRelationCode, function($value) { return $value !== ''; });

        $taskGroupRelationCodeArr = array_values(array_unique($filterTaskGroupRelationCode));

        if (count($filterTaskGroupRelationCode) != count($taskGroupRelationCodeArr)) {
            BaseService::throwErr("有重复的服务单号,请检查任务组");
        }

        $relationCodeCount = CruiseOrderModel::query()
            ->whereIn('relationCode', $taskGroupRelationCodeArr)
            ->count();

        if ($relationCodeCount) {
            BaseService::throwErr("有重复的服务单号,请检查任务组");
        }

        // 门店稽核 - 推送，必须供应商有审核人
        if ($task->templateType == CruiseTemplateModel::TYPE_3) {
            CruiseCheckTaskGroupModel::query()->where('taskId', $id)->where('companyId', '!=', '')->pluck('companyId')->unique()->values()->each(function ($departmentId) {

                $fsCompanyId = (int)FsCompanyModel::query()
                                                  ->where('departmentId', $departmentId)
                                                  ->where('status', FsCompanyModel::STATUS_ON)
                                                  ->value('id');
                if (!$fsCompanyId) {
                    BaseService::throwErr("供应商{$departmentId}不存在，或已被停用");
                }

                // 供应商角色
                $roles = FsCompanyRoleMappingModel::query()
                                                  ->where('fsCompanyId', $fsCompanyId)
                                                  ->whereIn('roleId', [
                                                      FsCompanyRoleMappingModel::ROLE_ID_COMPANY_FIRST,
                                                      FsCompanyRoleMappingModel::ROLE_ID_KF_REVIEWER
                                                  ])
                                                  ->groupBy('roleId')
                                                  ->get()->count();

                if ($roles != 2) {
                    BaseService::throwErr("供应商{$departmentId}缺少审核人配置");
                }
            });
        }

        switch ($task->templateType) {
            case CruiseTemplateModel::TYPE_5:
                $orderIds      = CruiseCheckDetailModel::query()->where('taskId', $id)->pluck('orderId')->toArray();
                $cruiseCheckCompanyIds = CruiseOrderModel::query()
                    ->whereIn('id', $orderIds)
                    ->pluck('cruiseCheckCompanyId')->toArray();

                $task->cruiseTaskGroupsRel->each(function ($item) use ($id, $cruiseCheckCompanyIds, $task) {

                    foreach ($item->beCruiseCheckCompanyIdsArr as $cruiseCheckCompanyId) {

                        // 先检查有没有
                        if (in_array($cruiseCheckCompanyId, $cruiseCheckCompanyIds)) {
                            continue;
                        }

                        DB::beginTransaction();

                        if ($item->role == CruiseCheckTaskGroupModel::ROLE_USER) {
                            $userId    = $item->userId;
                            $companyId = '';
                        } else {
                            $userId    = 0;
                            $companyId = $item->companyId;
                        }

                        if ($item->role == CruiseCheckTaskGroupModel::ROLE_USER) {
                            $checkType = CruiseCheckDetailModel::CHECK_TYPE_INSIDE;
                        } elseif ($item->role == CruiseCheckTaskGroupModel::ROLE_COMPANY) {
                            $checkType = CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY;
                        } else {
                            $checkType = 0;
                        }

                        CruiseOrderService::addTaskDb('', 0, $id, $userId, $companyId,
                            ($task->templateType == CruiseTemplateModel::TYPE_5 ? CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL : CruiseTemplateModel::SYS_TEMPLATE_SPECIAL), $checkType, $task->templateId, $cruiseCheckCompanyId);

                        DB::commit();
                    }

                    // 消息推送
                    (new CruiseCheckFsService(null, null))->submitBatch($task, $item);
                });
                break;
            default:
                $orderIds      = CruiseCheckDetailModel::query()->where('taskId', $id)->pluck('orderId')->toArray();
                $pushedShopIds = CruiseOrderModel::query()
                    ->whereIn('id', $orderIds)
                    ->pluck('shopId')->toArray();

                $sendSmsUserIds = [];

                $task->cruiseTaskGroupsRel->each(function ($item) use ($id, $pushedShopIds, $task, &$sendSmsUserIds) {

                    foreach ($item->shopIdsArr as $shopId) {

                        // 先检查有没有
                        if (in_array($shopId, $pushedShopIds)) {
                            continue;
                        }

                        DB::beginTransaction();

                        if ($item->role == CruiseCheckTaskGroupModel::ROLE_USER) {
                            $userId    = $item->userId;
                            $companyId = '';
                        } else {
                            $userId    = $item->userId;
                            $companyId = $item->companyId;
                        }

                        if ($item->role == CruiseCheckTaskGroupModel::ROLE_USER) {
                            $checkType = CruiseCheckDetailModel::CHECK_TYPE_INSIDE;
                        } elseif ($item->role == CruiseCheckTaskGroupModel::ROLE_COMPANY) {
                            $checkType = CruiseCheckDetailModel::CHECK_TYPE_THIRD_PARTY;
                        } else {
                            $checkType = 0;
                        }

                        CruiseOrderService::addTaskDb('', $shopId, $id, $userId, $companyId,
                            ($task->templateType == CruiseTemplateModel::TYPE_5 ? CruiseTemplateModel::SYS_TEMPLATE_FACTORY_SPECIAL : CruiseTemplateModel::SYS_TEMPLATE_SPECIAL), $checkType, $task->templateId, 0, $item->relationCode);

                        DB::commit();
                    }

                    // 消息推送
                    $sendSmsUserIds = array_merge((new CruiseCheckFsService(null, null))->submitBatch($task, $item), $sendSmsUserIds);
                });

                // 给三方审核人发送短信通知
                if (count($sendSmsUserIds)) {

                    $userAllInfo = RmsUserService::getRmsUserInfoByUserIds(array_values(array_unique($sendSmsUserIds)))['data'] ?? [];

                    // 获得待领取数量
                    $cruiseOrderIds = CruiseCheckDetailModel::query()
                        ->where('taskId', $task->id)
                        ->pluck('orderId')
                        ->toArray();

                    $taskNum = (int)CruiseOrderModel::query()
                        ->whereIn('id', $cruiseOrderIds)
                        ->where('status', CruiseOrderModel::STATUS_COLLECTED)
                        ->count();

                    if ($taskNum) {
                        foreach (array_unique($sendSmsUserIds) as $sendSmsUserId) {
                            $sendSmsMobile = collect($userAllInfo)->where('id', $sendSmsUserId)->first()['mobile'] ?? '';
                            if (strlen($sendSmsMobile)) {
                                try {
                                    CruiseCheckSmsService::sendInspectionTask($sendSmsMobile, $taskNum, $task->name, '待领取');
                                } catch (\Exception $exception) {}
                            }
                        }
                    }
                }
        }





        $task->status = CruiseCheckTaskModel::STATUS_ING;
        $task->save();
    }

    /**
     * 获得某个用户下存在的供应商
     * @param int $userId
     * @return array
     */
    public static function getNormalFsCompanyIds(int $userId): array
    {
        $fsCompanyIds = collect(CruiseCheckCompanyService::qualityControlCompanyList())->pluck('id')->toArray();

        return FsCompanyUserMappingModel::query()
            ->where('rmsUserId', $userId)
            ->whereIn('fsCompanyId', $fsCompanyIds)
            ->pluck('fsCompanyId')
            ->toArray();
    }
}
